import { addCollectUsingPost, delCollectUsingPost } from "@/services/novel-web/collectController";
import { addCommentUsingPost, pageNovelCommentUsingGet } from "@/services/novel-web/commentController";
import { getNovelInfoUsingGet } from "@/services/novel-web/novelController";
import { MessageError, ToLogin } from "@/utils/commonUtils";
import { LikeFilled, LikeOutlined, MessageOutlined, StarFilled, StarOutlined, StarTwoTone } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-components";
import { history, useParams } from "@umijs/max";
import { Avatar, Button, Card, Col, List, message, Row, Space, Tag, Typography } from "antd";
import React, { useEffect, useState } from "react";
import styles from './index.less';
import { addCommentLikeUsingPost, listCommentIsLikeUsingGet } from "@/services/novel-web/commentLikeController";
import { Comment } from "@ant-design/compatible";
import LikeIcon from "./components/LikeIcon";
import TextArea from "antd/es/input/TextArea";
import { ErrorCode } from "@/models/constant";
const {Title,Text,Paragraph} = Typography;

const NovelPage : React.FC = ()=>{
  // url :id
  const {id:novelId} = useParams<{id: string}>();
  // novel
  const [info,setInfo] = useState<API.NovelInfo>();

  const loadNovelInfo = async (id:string) => {
    try {
      const resp = await getNovelInfoUsingGet({
        id: Number(id),
      });
      setInfo(resp.data);

    } catch (error: any) {
      MessageError(error);
    }
  };

  // comments
  const [comments,setComments] = useState<API.PageCommentVO_>();
  const loadComments = async (id:number,page?,pageSize?) =>{
    try {
      const resp = await pageNovelCommentUsingGet({
        novelId: id,
        current: page,
        pageSize: pageSize,
        sortField: 'createTime',
        sortOrder: 'descend',
      })

      setComments(resp.data);

    } catch (error) {
      MessageError(error);
    }
  };    

  // islike
  const [likedComments, setLikedComments] = useState<number[]>([]);

  const loadLikedComments = async (novelId:number)=>{
    try {
      const resp = await listCommentIsLikeUsingGet({
        novelId: novelId,
      });

      setLikedComments(resp.data ?? []);
      

    } catch (error) {
      // no login => pass
      // MessageError(error);
    }
  };

  const isLike = (commentId:number) =>{
    return likedComments?.includes(commentId);
  }

  useEffect(()=>{
    if(novelId == '0') {
      history.push("/");
    }
    loadNovelInfo(novelId ?? '');
    loadComments(Number(novelId));
    loadLikedComments(Number(novelId));
  },[])

 


  // writer
  const handleWriteClick = (userId) =>{
    history.push("/user/"+userId);
  };

  // tag
  const handleTagClick = (tagId)=>{
    history.push("/search?tags="+tagId);
  };

  // collect Buutton
  const handleCollect = async () =>{
    try {
      const resp = await addCollectUsingPost({
        novelId: info?.id ?? 0
      });

      setInfo({
        ...info,
        isCollected: true,
        collectNum: info?.collectNum ? (info?.collectNum +1) : 0
      });
      message.success('收藏成功');

    } catch (error:any) {
      MessageError(error);
      ToLogin();
    }
  };

  const handleDisCollect = async () =>{
    try {
      const resp = await delCollectUsingPost({
        novelId: info?.id ?? 0
      });

      setInfo({
        ...info,
        isCollected: false,
        collectNum: info?.collectNum ? (info?.collectNum - 1) : 0
      });
      message.success('取消收藏成功');

    } catch (error:any) {
      MessageError(error);
      ToLogin();
    }
  };

  // pagination
  const handleCommentPageChange = (novelId,page, pageSize) =>{
    loadComments(novelId,page,pageSize);
  };


  // comment op
  const [activeReplyId,setActiveReplyId] = useState(0);
  const [replyContent,setReplyContent] = useState('');
  const handleCommentClick = (item: API.CommentVO) => {
    setReplyContent('');
    // 取消回复
    if(activeReplyId == item.id) {
      setActiveReplyId(0);
    } else {
      setActiveReplyId(item.id ?? 0);
    }
  };
  const handleSubmitReply = async (
    content:string,
    novelId: number,
    topId: number,
    parentId: number,
    replierId: number,
  ) =>{
    try {
      const resp = await addCommentUsingPost({
        content: content,
        novelId: novelId,
        topId: topId,
        parentId: parentId,
        replierId: replierId,
      });
      loadComments(Number(novelId),comments?.current);
      message.success('评论成功');
    } catch (error: any) {
      MessageError(error);
      if(error.info.code == ErrorCode.NOT_LOGIN_401) {
        ToLogin();
      }
      
    }

  };

  // top comment op
  const [topContent,setTopContent] = useState('');

  

  // comment actions
  const CommentActions = (item:API.CommentVO) =>{
    return [
      <LikeIcon
        className={styles.iconButton}
        likes={item.likes ?? 0}
        isliked={item.id ? isLike(item.id) :false}
        commentId={item.id ?? 0}
        novelId={Number(novelId)}
      />,
      <IconText
        className={styles.iconButton}
        style={{marginLeft: 16}} 
        key="list-vertical-message"
        icon={MessageOutlined} 
        text={'' +(item.replies? item.replies?.length : 0)}
      />,
      <span
        style={{marginLeft: 16}}  
        key="comment-nested-reply-to"
        onClick={()=>handleCommentClick(item)}
      >
        回复
      </span>
    ];
  };


  return (
    <PageContainer
      header={{
        ghost: true,
        breadcrumb:{
          items: [
            {
              href: '/welcome',
              title: '首页',
            },
            {
              title: info?.name,
            }
          ]
        },
      }}
    ><div className={styles.page}><Col>
      {/* novel */}
      <Card className={styles.card}>
        <Row>
          <img alt={info?.name} src={info?.cover} className={styles.cover}></img>
          <Col style={{marginLeft: 20}}>
            <Title level={3}  // className={styles.novelTitle}
            >{info?.name}</Title>
            <Row align="middle">
              <Avatar 
                src={info?.user?.avatar}
                className={styles.avatar}
                onClick={()=>handleWriteClick(info?.user?.id)}
              />
              <Text 
                style={{marginLeft: 8}}
                className={styles.userText} 
                onClick={()=>handleWriteClick(info?.user?.id)}
              >
                {info?.user?.nickname}
              </Text>
            </Row>
        
            <div style={{ marginTop: 8 }}>
              {/* <Text>{info?.isEnd ?"完结  ":"连载  "}</Text> */}
              <Tag>{info?.isEnd?"完结":"连载"}</Tag>
              {info?.tags?.map(tag => (
                <Tag key={tag.id} className={styles.tag}
                  onClick={()=> handleTagClick(tag.id)}
                >{tag.name}</Tag>
              ))}
            </div>
            <div style={{ marginTop: 16 }}>
              {/* <Button icon={<LikeOutlined />} style={{ marginRight: 8 }}>{"赞 "+info?.num}</Button> */}
              <Button href={`/novel/${novelId}/chapters`}>
                开始阅读
              </Button>
              <Button 
                icon={info?.isCollected ?<StarFilled style={{color:'#1890ff'}}/> : <StarOutlined/>} 
                style={{ marginLeft: 8 }}
                onClick={()=>{
                  info?.isCollected 
                  ? handleDisCollect()
                  : handleCollect();
                }}
              >
                {info?.isCollected
                  ?"已收藏  " + (info?.collectNum == 0 ? 1 : info?.collectNum)
                  :"收藏  "+ info?.collectNum 
                }
              </Button>
            </div>
            
          </Col>
        </Row>
      </Card>

      {/* description */}
      <Card style={{marginTop: 16}} className={styles.card}>
        <Title level={3}>作品简介</Title>
        <Paragraph 
          className={styles.description}
        >
          {info?.description}
        </Paragraph>
      </Card>
        
      {/* 评论区 */}
      <Card style={{marginTop: 16,}} className={styles.commentCard}>
        <Row align="middle">
          <Col><Title level={3}>评论</Title></Col>
          <Title style={{marginLeft: 8}}
            level={4} 
            type="secondary" 
          >{`共 ${comments?.total} 条`}</Title>
        </Row>

        {/* 顶部评论发布区 */}
        <div style={{ marginTop: 16 }} className={styles.topComment}>
          <TextArea
            rows={4}
            value={topContent}
            onChange={(e) => setTopContent(e.target.value)}
            placeholder="输入评论内容"
          />
          {/* <div className={styles.topComment.btn}> */}
          <Button
            type="primary"
            // loading={loading}
            onClick={() => {
              handleSubmitReply(
                topContent,
                Number(novelId),
                0,
                0,
                0,
              );
              setTopContent('');
              
            }}
            style={{ marginTop: 16,marginLeft: 8 }}
          >
            提交
          </Button>
          {/* </div> */}
        </div>

        <List
           className={styles.list}
           style={{marginTop: 16}}
          //  header={`${data.length} replies`}
          itemLayout="horizontal"
          dataSource={comments?.records}
          renderItem={item =>(
            <li><Comment 
              avatar={item.user?.avatar}
              author={item.user?.nickname}
              content={item.content}
              actions={CommentActions(item)}
            >
              {/* 显示回复区域 */}
              {activeReplyId == item.id && (
                <div style={{ marginTop: 16 }}>
                  <TextArea
                    rows={4}
                    value={replyContent}
                    onChange={(e) => setReplyContent(e.target.value)}
                    placeholder="输入回复内容"
                  />
                  <Button
                    type="primary"
                    // loading={loading}
                    onClick={() => {
                      handleSubmitReply(
                        replyContent,
                        Number(novelId),
                        item.id ?? -1,
                        item.id ?? -1,
                        0,
                      );
                      setActiveReplyId(0);
                    }}
                    style={{ marginTop: 8 }}
                  >
                    提交
                  </Button>
                </div>
              )}

              {/* 子评论 */}
              {item.replies && item.replies.length > 0 && (
                item.replies.map(item1 =>{
                  return(
                    <Comment
                      avatar={item1.user?.avatar}
                      author={item1.user?.nickname}
                      content={
                        (item1.replier?`回复 @${item1.replier.nickname} :`:'')
                        + item1.content
                      }
                      actions={CommentActions(item1)}
                    >
                      {/* 显示回复区域 */}
                      {activeReplyId == item1.id && (
                        <div style={{ marginTop: 16 }}>
                          <TextArea
                            rows={4}
                            value={replyContent}
                            onChange={(e) => setReplyContent(e.target.value)}
                            placeholder="输入回复内容"
                          />
                          <Button
                            type="primary"
                            // loading={loading}
                            onClick={() => {
                              handleSubmitReply(
                                replyContent,
                                Number(novelId),
                                item.id ?? -1,
                                item1.id ?? -1,
                                item1.user?.id ?? -1,
                              );
                              setActiveReplyId(0);
                            }}
                            style={{ marginTop: 8 }}
                          >
                            提交
                          </Button>
                        </div>
                      )}
                      
                    </Comment>
                  );
                })
              )}
                        
            </Comment></li>           
          )}
          pagination={{
            align: 'center',
            position: 'bottom',
            total: comments?.total,
            current: comments?.current,
            showSizeChanger: false,
            onChange(page, pageSize) {
              handleCommentPageChange(Number(novelId),page,pageSize);
            },
          }}
        >
        </List>

      </Card>

    </Col></div></PageContainer>
  );
};


const IconText = ({ icon, text,onclick,style,className }: { icon: React.FC; text: string; onclick?: ()=> void; style?:any;className?:any}) => (
  <Space onClick={onclick} style={style} className={className}>
    {React.createElement(icon)}
    {text}
  </Space>
);







export default NovelPage;